package com.oak.broke.model.vip.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oak.broke.constant.CommonConstant;
import com.oak.broke.constant.ResponseConstant;
import com.oak.broke.constant.VipConstant;
import com.oak.broke.exception.VipException;
import com.oak.broke.model.vip.service.ICommonFileService;
import com.oak.broke.model.vip.service.ITsDmService;
import com.oak.broke.model.vip.service.IVipOpenRecordService;
import com.oak.broke.model.vip.service.IVipUserService;
import com.oak.broke.utils.DateUtil;
import com.oak.broke.model.vip.dao.VipApplyDao;
import com.oak.broke.model.vip.dao.VipUserDao;
import com.oak.broke.model.vip.dto.BaseFileInfoDTO;
import com.oak.broke.model.vip.dto.api.SaveVipUserDTO;
import com.oak.broke.model.vip.dto.api.UpdateVipUserDTO;
import com.oak.broke.model.vip.dto.api.VipRenewalDTO;
import com.oak.broke.model.vip.entity.VipOpenRecordEntity;
import com.oak.broke.model.vip.entity.VipUserEntity;
import com.oak.broke.model.vip.vo.VipApplyVO;
import com.oak.broke.model.vip.vo.api.BaseVipInfoVO;
import com.oak.broke.model.vip.vo.api.VipUserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;


/**
 * 会员等级表
 *
 * @author tanghan
 * @email broke@gmail.com
 * @date 2023-04-12 17:02:57
 */
@Slf4j
@Service("vipUserService")
public class VipUserServiceImpl extends ServiceImpl<VipUserDao, VipUserEntity> implements IVipUserService {

    @Autowired
    private ITsDmService tsDmService;

    @Autowired
    private IVipOpenRecordService vipOpenRecordService;

    @Autowired
    private ICommonFileService commonFileService;
    @Autowired
    private VipApplyDao vipApplyDao;

    @Override
    public List<VipUserVO> listAllVipUser(String vipUserType) {
        List<VipUserVO> vipUserList = baseMapper.listAllVipUser(vipUserType);
        for (VipUserVO vipUser : vipUserList) {
            handleVipStatus(vipUser);
            vipUser.setVipStatusName(tsDmService.getTsdmValByKindAndCode(VipConstant.VIP_STATUS_TS_DM_KIND, vipUser.getVipStatus()));
        }
        return vipUserList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveVipUser(SaveVipUserDTO saveVipUserDTO) {
        long start = System.currentTimeMillis();
        log.info("开始执行保存会员用户任务");
        String userRelationCode = saveVipUserDTO.getUserRelationCode();
        String vipUserType = saveVipUserDTO.getVipUserType();
        String vipUsername = saveVipUserDTO.getVipUsername();
        // 先校验是否已添加过会员
        if (baseMapper.checkVipUserExist(userRelationCode, vipUserType)) {
            log.error("会员用户名称为【{}】的用户已是会员", vipUsername);
            throw new VipException(ResponseConstant.VIP_USER_EXISTS);
        }
        // 保存会员用户信息
        VipUserEntity vipUser = new VipUserEntity();
        BeanUtils.copyProperties(saveVipUserDTO, vipUser);
        vipUser.setCreateTime(new Date());
        vipUser.setUpdateTime(new Date());
        // 计算会员到期日期-首次开通，以当前日期 为开始日
        vipUser.setVipExpireDate(DateUtil.add(new Date(), Calendar.MONTH, saveVipUserDTO.getRenewalDuration()));
        baseMapper.insert(vipUser);

        // 保存开通记录
        VipOpenRecordEntity vipOpenRecord = new VipOpenRecordEntity();
        BeanUtils.copyProperties(saveVipUserDTO, vipOpenRecord);
        vipOpenRecord.setVipExpireDate(vipUser.getVipExpireDate());
        vipOpenRecordService.saveVipOpenRecord(vipOpenRecord);
        // 保存文件信息
        BaseFileInfoDTO baseFileInfoDTO = new BaseFileInfoDTO();
        baseFileInfoDTO.setBizId(vipOpenRecord.getVipOpenRecordId());
        baseFileInfoDTO.setBizType(CommonConstant.COMMON_FILE_TYPE_VIP_OPEN_RECORD);
        baseFileInfoDTO.setCreateUserCode(saveVipUserDTO.getCreateUserCode());
        baseFileInfoDTO.setCreateUsername(saveVipUserDTO.getCreateUsername());
        commonFileService.saveFile(saveVipUserDTO.getFileList(), baseFileInfoDTO);
        log.info("保存会员信息任务结束，共耗时:{}毫秒", (System.currentTimeMillis() - start));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void vipRenewal(VipRenewalDTO vipRenewal) {
        VipUserEntity vipUser = baseMapper.selectVipUserByVipUserId(vipRenewal.getVipUserId());
        if (vipUser == null) {
            log.error("该用户未开通过会员，无法进行续费");
            throw new VipException(ResponseConstant.VIP_USER_NOT_OPEN);
        }
        int daysRemaining = DateUtil.daysBetween(new Date(), vipUser.getVipExpireDate(), true);
        // 如果会员状态是超期，则会员过期时间按照当前时间算
        if (daysRemaining <= 0) {
            vipUser.setVipExpireDate(DateUtil.add(new Date(), Calendar.MONTH, vipRenewal.getRenewalDuration()));
        } else {
            // 过期时间
            vipUser.setVipExpireDate(DateUtil.add(vipUser.getVipExpireDate(), Calendar.MONTH, vipRenewal.getRenewalDuration()));
        }
        vipUser.setUpdateTime(new Date());
        vipUser.setUpdateUsername(vipRenewal.getCreateUsername());
        vipUser.setUpdateUserCode(vipRenewal.getCreateUserCode());
        // 更新会员信息
        baseMapper.updateById(vipUser);

        VipOpenRecordEntity vipOpenRecord = new VipOpenRecordEntity();
        // 新增开通记录
        BeanUtils.copyProperties(vipUser, vipOpenRecord);
        vipOpenRecord.setRenewalDuration(vipRenewal.getRenewalDuration());
        vipOpenRecord.setCreateUsername(vipRenewal.getCreateUsername());
        vipOpenRecord.setCreateUserCode(vipRenewal.getCreateUserCode());
        vipOpenRecord.setRenewalMoney(vipRenewal.getRenewalMoney());
        vipOpenRecordService.saveVipOpenRecord(vipOpenRecord);
        // 保存文件信息
        BaseFileInfoDTO baseFileInfoDTO = new BaseFileInfoDTO();
        baseFileInfoDTO.setBizId(vipOpenRecord.getVipOpenRecordId());
        baseFileInfoDTO.setBizType(CommonConstant.COMMON_FILE_TYPE_VIP_OPEN_RECORD);
        baseFileInfoDTO.setCreateUserCode(vipRenewal.getCreateUserCode());
        baseFileInfoDTO.setCreateUsername(vipRenewal.getCreateUsername());
        commonFileService.saveFile(vipRenewal.getFileList(), baseFileInfoDTO);
    }

    @Override
    public VipUserVO selectVipUserInfo(String vipUserId) {
        VipUserVO vipUser = baseMapper.selectVipUser(vipUserId);
        if (vipUser == null) {
            log.error("会员id为【{}】的会员用户不存在!", vipUserId);
            throw new VipException(ResponseConstant.VIP_USER_NOT_EXIST);
        }
        handleVipStatus(vipUser);
        vipUser.setVipStatusName(tsDmService.getTsdmValByKindAndCode(VipConstant.VIP_STATUS_TS_DM_KIND, vipUser.getVipStatus()));
        return vipUser;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateVipUser(UpdateVipUserDTO updateVipUser) {
        VipUserEntity vipUser = baseMapper.selectVipUserByVipUserId(updateVipUser.getVipUserId());
        if (vipUser == null) {
            log.error("会员id为【{}】的会员用户不存在!", updateVipUser.getVipUserId());
            throw new VipException(ResponseConstant.VIP_USER_NOT_EXIST);
        }
        vipUser.setContacts(updateVipUser.getContacts());
        vipUser.setContactsPhone(updateVipUser.getContactsPhone());
        vipUser.setVipLevelId(updateVipUser.getVipLevelId());
        vipUser.setUpdateUserCode(updateVipUser.getUpdateUserCode());
        vipUser.setUpdateUserCode(updateVipUser.getUpdateUserCode());
        vipUser.setUpdateTime(new Date());
        baseMapper.updateById(vipUser);
    }

    @Override
    public BaseVipInfoVO selectVipInfo(String userRelationCode, String vipUserType) {
        BaseVipInfoVO vipInfo = baseMapper.selectVipInfo(userRelationCode, vipUserType);
        if (vipInfo == null) {
            vipInfo = new BaseVipInfoVO();
            setApplyUser(userRelationCode,vipUserType, vipInfo);
            vipInfo.setVipStatus(VipConstant.VIP_STATUS_NOT_OPEN);
            return vipInfo;
        }
        handleVipStatus(vipInfo);
        setApplyUser(userRelationCode,vipUserType, vipInfo);
        return vipInfo;
    }

    private void setApplyUser(String userRelationCode, String vipUserType,BaseVipInfoVO vipInfo){
        // 最新申请的用户的记录
        List<VipApplyVO> applyUsers = vipApplyDao.vipApplyUserList(userRelationCode, vipUserType);
        if(CollUtil.isNotEmpty(applyUsers)){
            VipApplyVO applyUser = applyUsers.get(0);
            vipInfo.setUserName(applyUser.getUserName());
            vipInfo.setPhone(applyUser.getPhone());
        }
    }

    /**
     * 处理会员状态
     *
     * @param vipUser 会员信息
     */
    private void handleVipStatus(BaseVipInfoVO vipUser) {
        int daysRemaining = DateUtil.daysBetween(new Date(), vipUser.getVipExpireDate(), true);
        vipUser.setVipDaysRemaining(daysRemaining);
        if (daysRemaining >= 30) {
            vipUser.setVipStatus(VipConstant.VIP_STATUS_EFFECTIVE);
        } else if (daysRemaining > 0) {
            vipUser.setVipStatus(VipConstant.VIP_STATUS_NEAR_EXPIRE);
        } else {
            vipUser.setVipDaysRemaining(0);
            vipUser.setVipStatus(VipConstant.VIP_STATUS_EXPIRE);
        }
    }
}
